package com.example.sprintboot.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

/**
 * HTTP请求工具类
 * 封装常用的HTTP请求操作，减少重复代码
 */
@Component
public class HttpUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送GET请求
     * 
     * @param url 请求URL
     * @param queryParams 查询参数
     * @param responseType 响应类型
     * @return HTTP响应结果
     */
    public <T> HttpResult<T> get(String url, Map<String, Object> queryParams, Class<T> responseType) {
        try {
            // 构建带查询参数的URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            if (queryParams != null) {
                queryParams.forEach(builder::queryParam);
            }
            String finalUrl = builder.toUriString();

            // 发送GET请求
            ResponseEntity<String> response = restTemplate.exchange(
                    finalUrl,
                    HttpMethod.GET,
                    null,
                    String.class
            );

            // 解析响应
            T data = parseResponse(response.getBody(), responseType);
            return HttpResult.success(data, response.getBody());

        } catch (HttpClientErrorException e) {
            return HttpResult.error(e.getStatusCode().value(), e.getResponseBodyAsString(), e.getMessage());
        } catch (Exception e) {
            return HttpResult.error(-1, null, "请求异常: " + e.getMessage());
        }
    }

    /**
     * 发送POST请求
     * 
     * @param url 请求URL
     * @param queryParams 查询参数
     * @param requestBody 请求体
     * @param responseType 响应类型
     * @return HTTP响应结果
     */
    public <T> HttpResult<T> post(String url, Map<String, Object> queryParams, Object requestBody, Class<T> responseType) {
        return post(url, queryParams, requestBody, responseType, null);
    }

    /**
     * 发送POST请求（带自定义请求头）
     * 
     * @param url 请求URL
     * @param queryParams 查询参数
     * @param requestBody 请求体
     * @param responseType 响应类型
     * @param customHeaders 自定义请求头
     * @return HTTP响应结果
     */
    public <T> HttpResult<T> post(String url, Map<String, Object> queryParams, Object requestBody, 
                                  Class<T> responseType, Map<String, String> customHeaders) {
        try {
            // 构建带查询参数的URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            if (queryParams != null) {
                queryParams.forEach(builder::queryParam);
            }
            String finalUrl = builder.toUriString();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            if (customHeaders != null) {
                customHeaders.forEach(headers::set);
            }

            // 创建请求实体
            HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);

            // 打印请求信息（调试用）
            logRequest("POST", finalUrl, requestBody, headers);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    finalUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            // 打印响应信息（调试用）
            logResponse(response);

            // 解析响应
            T data = parseResponse(response.getBody(), responseType);
            return HttpResult.success(data, response.getBody());

        } catch (HttpClientErrorException e) {
            logError("POST", url, e);
            return HttpResult.error(e.getStatusCode().value(), e.getResponseBodyAsString(), e.getMessage());
        } catch (Exception e) {
            return HttpResult.error(-1, null, "请求异常: " + e.getMessage());
        }
    }

    /**
     * 发送PUT请求
     */
    public <T> HttpResult<T> put(String url, Map<String, Object> queryParams, Object requestBody, Class<T> responseType) {
        try {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            if (queryParams != null) {
                queryParams.forEach(builder::queryParam);
            }
            String finalUrl = builder.toUriString();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    finalUrl,
                    HttpMethod.PUT,
                    requestEntity,
                    String.class
            );

            T data = parseResponse(response.getBody(), responseType);
            return HttpResult.success(data, response.getBody());

        } catch (HttpClientErrorException e) {
            return HttpResult.error(e.getStatusCode().value(), e.getResponseBodyAsString(), e.getMessage());
        } catch (Exception e) {
            return HttpResult.error(-1, null, "请求异常: " + e.getMessage());
        }
    }

    /**
     * 发送DELETE请求
     */
    public <T> HttpResult<T> delete(String url, Map<String, Object> queryParams, Class<T> responseType) {
        try {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
            if (queryParams != null) {
                queryParams.forEach(builder::queryParam);
            }
            String finalUrl = builder.toUriString();

            ResponseEntity<String> response = restTemplate.exchange(
                    finalUrl,
                    HttpMethod.DELETE,
                    null,
                    String.class
            );

            T data = parseResponse(response.getBody(), responseType);
            return HttpResult.success(data, response.getBody());

        } catch (HttpClientErrorException e) {
            return HttpResult.error(e.getStatusCode().value(), e.getResponseBodyAsString(), e.getMessage());
        } catch (Exception e) {
            return HttpResult.error(-1, null, "请求异常: " + e.getMessage());
        }
    }

    /**
     * 解析响应数据
     */
    private <T> T parseResponse(String responseBody, Class<T> responseType) throws Exception {
        if (responseBody == null || responseBody.trim().isEmpty()) {
            return null;
        }
        
        if (responseType == String.class) {
            return responseType.cast(responseBody);
        }
        
        return objectMapper.readValue(responseBody, responseType);
    }

    /**
     * 打印请求信息（调试用）
     */
    private void logRequest(String method, String url, Object requestBody, HttpHeaders headers) {
        try {
            System.out.println("=== HTTP请求信息 ===");
            System.out.println("方法: " + method);
            System.out.println("URL: " + url);
            if (requestBody != null) {
                System.out.println("请求体: " + objectMapper.writeValueAsString(requestBody));
            }
            System.out.println("请求头: " + headers.toString());
            System.out.println("==================");
        } catch (Exception e) {
            System.err.println("打印请求信息失败: " + e.getMessage());
        }
    }

    /**
     * 打印响应信息（调试用）
     */
    private void logResponse(ResponseEntity<String> response) {
        System.out.println("=== HTTP响应信息 ===");
        System.out.println("状态码: " + response.getStatusCode());
        System.out.println("响应体: " + response.getBody());
        System.out.println("==================");
    }

    /**
     * 打印错误信息（调试用）
     */
    private void logError(String method, String url, HttpClientErrorException e) {
        System.err.println("=== HTTP错误信息 ===");
        System.err.println("方法: " + method);
        System.err.println("URL: " + url);
        System.err.println("状态码: " + e.getStatusCode());
        System.err.println("错误信息: " + e.getMessage());
        System.err.println("响应体: " + e.getResponseBodyAsString());
        System.err.println("==================");
    }

    /**
     * HTTP响应结果封装类
     */
    public static class HttpResult<T> {
        private boolean success;
        private int statusCode;
        private T data;
        private String rawResponse;
        private String errorMessage;

        private HttpResult() {}

        public static <T> HttpResult<T> success(T data, String rawResponse) {
            HttpResult<T> result = new HttpResult<>();
            result.success = true;
            result.statusCode = 200;
            result.data = data;
            result.rawResponse = rawResponse;
            return result;
        }

        public static <T> HttpResult<T> error(int statusCode, String rawResponse, String errorMessage) {
            HttpResult<T> result = new HttpResult<>();
            result.success = false;
            result.statusCode = statusCode;
            result.rawResponse = rawResponse;
            result.errorMessage = errorMessage;
            return result;
        }

        // Getters
        public boolean isSuccess() { return success; }
        public int getStatusCode() { return statusCode; }
        public T getData() { return data; }
        public String getRawResponse() { return rawResponse; }
        public String getErrorMessage() { return errorMessage; }
    }
}
